const { getMongooseClient, StringToObjectId } = require('../database/mongoose');

async function getMongoDBSession () {
    return getMongooseClient().startSession();
}

async function startTransaction (session) {
    await session.startTransaction({
        readConcern: { level: 'snapshot' },
        writeConcern: { w: 'majority' },
        readPreference: 'primary'
    });
    return session;
}

async function commitTransaction (session) {
    await session.commitTransaction();
    return session;
}

async function endSession (session) {
    await session.endSession();
    return 0;
}

async function abortTransaction (session) {
    await session.abortTransaction();
    return 0;
}

function getObjectId (value) {
    return StringToObjectId(value);
}

module.exports = {
    getMongoDBSession,
    startTransaction,
    commitTransaction,
    endSession,
    abortTransaction,
    getObjectId
};
